package com.anysoft.rrm;

import com.alogic.metrics.stream.MetricsHandlerFactory;
import com.anysoft.stream.Handler;
import com.anysoft.util.*;
import com.anysoft.util.resource.ResourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.InputStream;

/**
 * Handler工程
 * 
 * @since 1.6.12.32 [20190429] <br>
 * 
 */
public class RRDataHandlerFactory extends Factory<Handler<RRData>> {

    /**
     * a logger of log4j
     */
    protected static final Logger LOG = LoggerFactory.getLogger(RRDataHandlerFactory.class);

    private RRDataHandlerFactory(){

    }

    /**
     * 缺省配置文件
     */
    public static final String DEFAULT =
            "java:///com/anysoft/rrm/default.xml#" + RRDataHandlerFactory.class.getName();

    /**
     * 用于客户端的MetricsHandler
     */
    private static Handler<RRData> instance = null;

    /**
     * 获取客户端的唯一实例
     * @return client
     */
    public static Handler<RRData> getHandler(){
        if (instance == null){
            synchronized (MetricsHandlerFactory.class){
                if (instance == null){
                    Settings p = Settings.get();
                    String master = p.GetValue("rrm.master",DEFAULT);
                    String secondary = p.GetValue("rrm.secondary",DEFAULT);

                    instance = getInstance(master,secondary,p);
                }
            }
        }
        return instance;
    }

    /**
     * 根据环境变量中的配置来创建MetricsHandler
     */
    protected static Handler<RRData> getInstance(String master, String secondary, Properties props){
        ResourceFactory rf = Settings.getResourceFactory();
        InputStream in = null;
        try {
            in = rf.load(master,secondary, null);
            Document doc = XmlTools.loadFromInputStream(in);
            if (doc != null){
                return getInstance(doc.getDocumentElement(),props);
            }
        }catch (Exception ex){
            LOG.error("Error occurs when load xml file,source=" + master, ex);
        }finally {
            IOTools.closeStream(in);
        }
        return null;
    }

    public static Handler<RRData> getInstance(Element e, Properties p){
        RRDataHandlerFactory f = new RRDataHandlerFactory();
        return f.newInstance(e, p);
    }
}
